﻿using Identity.API.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;

namespace Identity.API.Models
{
    public class User : Entity<long>, IIdentity
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string Phone { get; set; }
        [Required]
        public string Email { get; set; }
        public string Password { get; set; }
        public string AuthenticationType { get; set; }
        public bool IsAuthenticated { get; set; }

        private readonly CustomDbContext dbContext;
        public User(CustomDbContext applicationDbContext)
        {
            dbContext = applicationDbContext;

            IsAuthenticated = false;
        }

        public async Task<IdentityResult> CreateAsync()
        {
            if (!dbContext.Users.Any(x => x.Name == Name))
            {
                var result = await dbContext.Users.AddAsync(this);
                //await dbContext.SaveChangesAsync();

                return IdentityResult.Success;
            }
            return IdentityResult.Failed(new IdentityError { Description = "创建用户失败。" });
        }
        public async Task<IdentityResult> DeleteAsync()
        {
            var user = await dbContext.Users.SingleOrDefaultAsync(x=>x.Name == Name);
            if(user != null)
            {
                dbContext.Users.Remove(user);
                //await dbContext.SaveChangesAsync();

                return IdentityResult.Success;
            }
            return IdentityResult.Failed(new IdentityError { Description = "删除用户失败。" });
        }

        public static async Task<User> FindByIdAsync(CustomDbContext dbContext, long id)
        {
            return await dbContext.Users.SingleOrDefaultAsync(x => x.Id == id);
        }

        public static async Task<User> FindByNameAsync(CustomDbContext dbContext, string username)
        {
            return await dbContext.Users.SingleOrDefaultAsync(x => x.Name == username);
        }

        public async Task SetPasswordAsync(string password)
        {
            var user = await dbContext.Users.SingleOrDefaultAsync(x => x.Id == Id);
            user.Password = password;
            //await dbContext.SaveChangesAsync();
        }
    }
}
